//---------------------------------------------------------------------
// Copyright (C) 2010 - Cobalt Solution / Sebastien Leon              |
//---------------------------------------------------------------------
// This software is under dual licence: commercial licence + GPL v3   |
// To keep closed your modification of this software, you need to     |
// contact me to obtain a commercial licence.                         |
// Any other derivated work should remain Open Source.                |
// Contact me for a licence, a question or if you want to commit      |
// your code to the main tree: seb at cobaltsolutions dot info        |
//---------------------------------------------------------------------

//#include <QList>
#include <QDateTime>
#include <QUrl>
#include <QDesktopServices>

#include "mainForm.h"
#include "Core.h"
#include "EditLoom.h"
#include "EditPref.h"
#include "About.h"

MainForm::MainForm(QWidget* parent, Core& loomfeed):
  QMainWindow(parent),
  mr_loomfeed(loomfeed),
  m_sysTray(this),
  m_dirModel (this)
{
  ui.setupUi(this);
  m_sysTray.setIcon(QIcon(":/logo.ico"));
  PathModified();
  OnSelectionChanged();
  ui.mp_lockUI->setChecked(true); // lock by default !

  // Initialize the dirModel:
  m_dirModel.setReadOnly ( true );
  ui.mp_treeView->setRootIsDecorated ( false );
  //ui.mp_treeView->setDragDropMode(QAbstractItemView::DragOnly);
  int nbH = ui.mp_treeView->header()->count();
  for (int n = 1 ; n < nbH ; ++n) ui.mp_treeView->hideColumn(n);
  //ui.mp_treeView->header()->hide();

  // Prepare the view: 
  ui.mp_view->SetForm (*this);

  connect(&loomfeed,  SIGNAL(PathModified   ()), 
                      SLOT  (PathModified   ()));

  connect(&loomfeed,  SIGNAL(Message        (const QString&, QSystemTrayIcon::MessageIcon)), 
                      SLOT  (MessageFromCore(const QString&, QSystemTrayIcon::MessageIcon)));

  connect(ui.mp_treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), 
                                            SLOT(OnSelectionChanged()));

  statusBar()->showMessage ( "Bienvenue dans Loomfeed...", 10000 );
}
//----------------------------------------------------
QGraphicsScene& MainForm::LoomScene()
{
  return mr_loomfeed.LoomScene();
}
//----------------------------------------------------
void MainForm::ValidLoomPosSizeChange(Loom* l)
{
  mr_loomfeed.ValidLoomGraphicChange(l);
}
//----------------------------------------------------
void MainForm::PathModified()
{
  QModelIndex idx = m_dirModel.setRootPath ( mr_loomfeed.Path() );
  ui.mp_treeView->setModel(&m_dirModel);
  ui.mp_treeView->setRootIndex(idx);
}
//----------------------------------------------------
void MainForm::OnSelectionChanged()
{
  QString caption("Selection: %1");
  QString info   ("Infos: %1");
  QPixmap pix;

  // Extract info from tree view:
  QModelIndexList lst = ui.mp_treeView->selectionModel()->selection().indexes();
  if (lst.count() == 0)
  {
    caption = caption.arg("<i>aucune...</i>");
    info    = info   .arg("");
  }
  else if (lst.count() == 1)
  {
    if (m_dirModel.isDir(lst[0]))
    {
      caption = caption.arg("<i>1 repertoire</i>");
      info    = info   .arg("<i>selection ignoree...</i>");
    }
    else
    {
      QFileInfo nfo (m_dirModel.fileInfo(lst[0]));
      pix     = m_dirModel.fileIcon(lst[0]).pixmap(40,40);
      caption = caption.arg("<b>"+nfo.fileName()+"</b>");
      info    = info   .arg(QString("%1 Ko [%2]")
        .arg((float)nfo.size()/1024, 0, 'f', 2)
        .arg(nfo.lastModified().toString("dd MMM yyyy, hh:mm")));
    }
  }
  else // multi selection
  {
    caption = caption.arg(QString("<i>%1 fichiers, repertoires</i>").arg(lst.count()));
    info    = info   .arg("<i>les repertoires seront ignores...</i>");
  }

  ui.mp_selection->setText  (caption);
  ui.mp_fileInfo ->setText  (info   );
  ui.mp_icon     ->setPixmap(pix    );
}
//----------------------------------------------------
void MainForm::OnEditPref()
{
  EditPref dlg(this, mr_loomfeed, ui.mp_lockUI->isChecked());
  dlg.exec();
}
//----------------------------------------------------
void MainForm::OnLockUI ()
{
  bool enabled = !ui.mp_lockUI->isChecked();
  // Lock/Unlock ui:
  ui.mp_addLoom   ->setEnabled(enabled);
  // ui.mp_editPref  ->setEnabled(enabled); // pass a readonly flag rather...
}
//----------------------------------------------------
void MainForm::InitiateTransfer(QFileInfo& nfo, const Loom* p_loom)
{
  mr_loomfeed.InitiateTransfer(nfo, p_loom);
}
//----------------------------------------------------
void MainForm::OnPrint  ()
{
  QString path(mr_loomfeed.CreateReport(Core::e_Svg));
  if (!path.isEmpty()) QDesktopServices::openUrl( QUrl::fromLocalFile(path) );
}
//----------------------------------------------------
void MainForm::MessageFromCore(const QString& msg, QSystemTrayIcon::MessageIcon icon)
{
  if (icon == QSystemTrayIcon::Warning || icon == QSystemTrayIcon::Critical)
  {
    // We use System Tray for real issue:
    if (QSystemTrayIcon::supportsMessages())
    {
      m_sysTray.showMessage ( "Message de Loomdeed:", msg, icon, 10000 );
    }
    else statusBar()->showMessage ( msg, 20000 );
  }
  else
  {
    statusBar()->showMessage ( msg, 20000 );
  }
}
//----------------------------------------------------
void MainForm::OnHelp  ()
{
  About dlg(this);
  dlg.exec();
}
//----------------------------------------------------
void MainForm::OnAddLoom ()
{
  Loom* l = new Loom; // create a new empty one...
  EditLoom dlg(this, *l, EditLoom::e_create);
  while (true)
  {
    if (QDialog::Accepted == dlg.exec())
    {
      if (mr_loomfeed.AddLoom(l))
      {
        l = NULL; // Core take ownership. We don't want it to be deleted by the code below...
        break;
      }
      else
      {
        QString msg("Loomfeed n'accepte pas votre nouvelle entree.\nCela est du au fait qu'un controleur existant possede deja le meme nom ou la meme adresse IP.\nModifiez ces parametres, svp...");
        // "Loomfeed refused to register your new Loom. Please check that you are not using the same name or the same IP address that another existing loom..."
        QMessageBox::warning ( this, "Message de Loomfeed", msg);
      }
    }
    else break;
  }
  delete l; // will do nothing if l is NULL
}
//----------------------------------------------------
void MainForm::DblClickItem(QGraphicsItem* item)
{
  // is it a Loom ?
  const Loom* l = dynamic_cast<const Loom*>(item);

  if (l)
  {
    // Make a copy:
    Loom tmpLoom(*l);
    EditLoom dlg(this, tmpLoom, IsReadOnly() ? EditLoom::e_show : EditLoom::e_edit);
    while (true)
    {
      EditLoom::EReturnCode res = (EditLoom::EReturnCode)dlg.exec();
      if (res == EditLoom::e_reject) break;
      if (res == EditLoom::e_remove) { mr_loomfeed.DeleteLoom(l); break; }
      if (res == EditLoom::e_accept) 
      {
        if (IsReadOnly())
        {
          break;
        }
        else
        {
          if (mr_loomfeed.UpdateLoom(l, tmpLoom)) // Edit...
          {
            break;
          }
          else
          {
            QString msg("Loomfeed n'accepte pas vos modifications.\nCela est du au fait qu'un controleur existant possede deja le meme nom ou la meme adresse IP.\nModifiez ces parametres, svp...");
            // "Loomfeed refused to change your loom properties. Please check that you are not using the same name or the same IP address that another existing loom..."
            QMessageBox::warning ( this, "Message de Loomfeed", msg);
          }
        }
      }
    }
  }
}
//----------------------------------------------------
